package com.dream.wukong.configcenter.client.remote.http;

import com.alibaba.fastjson.JSONArray;
import com.dream.wukong.configcenter.client.core.util.ConfigConstant;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.List;

/**
* 描  述:
* 创建时间: 2018/5/22
*/
public class HttpSourceConverter {

    private static Logger logger = Logger.getLogger(HttpSourceConverter.class);

    private static List<String> configUrls = Lists.newArrayList();

    private static List<String> remoteApiGetSources(String url) {
        List<String> resources = Lists.newArrayList();
        String result = HttpServer.getInstance().getServerResource(url, null);
        if (StringUtils.isNotBlank(result))
        {
            JSONArray jsonArray = JSONArray.parseArray(result);
            ArrayList<Object> jsons = Lists.newArrayList(jsonArray.iterator());
            if(CollectionUtils.isNotEmpty(jsons)){
                jsons.forEach(json -> {
                    resources.add(json.toString());
                });
            }
        }
        return  resources;
    }


    public static List<String> analyzeUrl(String defaultConfigDirectoryUrl,String serviceConfigDirectoryUrl) {
        if (CollectionUtils.isEmpty(configUrls)) {
            List<String> configUrlsList = Lists.newArrayList();
            List<String> sources = remoteApiGetSources(defaultConfigDirectoryUrl);
            if(CollectionUtils.isNotEmpty(sources)){
                sources.forEach(sourceName -> {
                    configUrlsList.add(defaultConfigDirectoryUrl + sourceName);
                });
            }
            sources = remoteApiGetSources(serviceConfigDirectoryUrl);
            if(CollectionUtils.isNotEmpty(sources)){
                sources.forEach(sourceName -> {
                    configUrlsList.add(serviceConfigDirectoryUrl + sourceName);
                });
            }
            configUrls.addAll(configUrlsList);
        }
        return configUrls;
    }

    public static List<String> getSourceNames(String defaultConfigDirectoryUrl, String serviceConfigDirectoryUrl) {
        List<String> sourceNames = Lists.newArrayList();
        List<String> urls = analyzeUrl(defaultConfigDirectoryUrl, serviceConfigDirectoryUrl);
        if(CollectionUtils.isNotEmpty(urls)){
            urls.forEach(url -> {
                String sourceName = ConfigConstant.getServiceName(url,defaultConfigDirectoryUrl,serviceConfigDirectoryUrl);
                if(!sourceNames.contains(sourceName)){
                    sourceNames.add(sourceName);
                }
            });
        }
        return sourceNames;
    }
}
